package com.zj.transactionspringboot01.service.impl;

import com.zj.transactionspringboot01.domain.Teacher;
import com.zj.transactionspringboot01.service.IteacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

//还没有引入mybatis包，暂时不用mybatis
@Service
public class TeacherServiceImpl implements IteacherService {
    TeacherServiceImpl() {
        System.out.println("TeacherServiceImpl");
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int addTeacher(Teacher teacher) {
        String sql = "insert into teacher(name ,sex,phoneNum,idno,address) values(?,?,?,?,?)";
        int res = jdbcTemplate.update(sql, teacher.getName(), teacher.getSex(), teacher.getPhonenum(), teacher.getIdno(), teacher.getAddress());
        int a=1/0;
        return res;
    }

    @Override
    @Transactional(readOnly = true)//readonly只能标注在selelct方法上，方法中由修改会报异常
    public int deleteTeacher(Integer id) {
        String sql = "delete from teacher where id =?";
        int res = jdbcTemplate.update(sql, id);
        return res;
    }

    @Override
    @Transactional
    public int updateTeacher(Teacher teacher) {
        String sql = "update teacher set name=?,phonenum=? ,address=? where  idno=?";
        int res = jdbcTemplate.update(sql, teacher.getName(), teacher.getPhonenum(), teacher.getAddress(), teacher.getIdno());
//        int a=1/0;
        return res;
    }

    @Override
    public int updateTeacherByName(Teacher teacher) {
        String sql = "update teacher set phonenum=? ,address=? where  name=?";
        int res = jdbcTemplate.update(sql,  teacher.getPhonenum(), teacher.getAddress(), teacher.getName());
//        int a=1/0;
        return res;
    }

    @Override
    @Transactional(readOnly = true)
    public Teacher selectTeacher(Integer id) {
        String sql = "select * from teacher where idno=?";
        Teacher teacher = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Teacher.class), id);

        return teacher;
    }

    @Override
    public List<Teacher> selectTeachers() {
        String sql = "select * from teacher ";
        List<Teacher> teachers = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Teacher.class));
        return teachers;
    }
}
